<template>
  <div class="app-container-table">
    <div class="header">
      <div class="select-theme">
        <span class="select-title">主题</span>
        <el-cascader v-model="category" :options="categories" :show-all-levels="false" placeholder="点击或输入查找主题" :filter-method="filterMethod" filterable @change="toRefresh" />
      </div>
      <div class="select-status">
        <span class="select-title">状态</span>
        <el-select v-model="status" @change="toRefresh">
          <el-option key="1" value="-1" label="全部" selected />
          <el-option key="2" value="1" label="已提交" />
          <el-option key="3" value="2" label="未提交" />
          <el-option key="4" value="3" label="不可见" />
        </el-select>
      </div>
      <span class="select-title">搜索 :</span>
      <div class="select-scan">
        <el-input v-model="title" placeholder="输入需要搜索的内容" />
      </div>

    </div>

    <el-table
      v-loading="this.$store.state.loading.isLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="标题" width="540">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top">
            <div slot="content">{{ scope.row.tabloid }}</div>
            <div>
              <span v-html="scope.row.title" />
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="封面" width="60" align="center">
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            trigger="hover"
          >
            <icon slot="reference" class="el-icon-picture" style="font-size: 24px" />
            <img :src="scope.row.coverImg" alt="" style="width: 300px;height: 200px;cursor: pointer" @error="handlerImgError">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="作者" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="80" align="center">
        <template slot-scope="scope">{{ scope.row.type }}</template>
      </el-table-column>
      <el-table-column label="主题" width="140" align="center">
        <template slot-scope="scope">{{ scope.row.category }}</template>
      </el-table-column>
      <el-table-column class-name="status-col" label="标签" width="150" align="center">
        <template slot-scope="scope">
          <el-tag
            v-for="(tag,index) in scope.row.tags"
            :key="index"
            size="mini"
            type="success"
            style="font-size: small"
          >{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter" effect="dark">{{ scope.row.status | mapFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="最近更新日期" label="更新日期" width="120">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.gmtUpdate }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="创建日期" label="创建日期" width="120">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.gmtCreate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="light" content="修改文章" placement="top-start">
            <el-button type="primary" icon="el-icon-edit" @click="$router.push({name: 'Tree',query: {articleId: scope.row.id}})" />
          </el-tooltip>
          <el-tooltip class="item" effect="light" content="删除文章" placement="top-start">
            <el-button type="danger" icon="el-icon-delete" @click="deleteArticle(scope.row.id,scope.row.title)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :hide-on-single-page="true"
      :current-page="pageInfo.current"
      :page-size="pageInfo.pageSize"
      layout=" prev, pager, next, jumper"
      :total="pageInfo.total"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { getList } from '@/api/table'
import { getAllCategory } from '@/api/category'
const { deleteArticle } = require('@/api/table')
// 节流函数
// eslint-disable-next-line no-unused-vars
const delay = (function() {
  let timer = 0
  return function(callback, ms) {
    clearTimeout(timer)
    timer = setTimeout(callback, ms)
  }
})()
export default {
  filters: {
    // 通过状态获取颜色
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        sightless: ''
      }
      return statusMap[status]
    },
    mapFilter(status) {
      const mapMap = {
        published: '已提交',
        draft: '未提交',
        sightless: '不可见'
      }
      return mapMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      pageInfo: null,
      categories: [],
      // 限制查询参数
      status: '-1',
      title: '',
      category: '',
      // ///////////////
      defaultPage: 1,
      defaultLimit: 6,
      statusMap: ['published', 'draft', 'sightless']
    }
  },
  watch: {
    title() {
      delay(() => {
        this.toRefresh()
      }, 300)
    }
  },
  created() {
    this.categories = getAllCategory()
    this.categories.push({ label: '全部', show: false })
    this.toRefresh()
  },
  methods: {
    filterMethod(node, keyword) {
      return node.label.toUpperCase().indexOf(keyword.toUpperCase()) !== -1
    },
    delay() {
      let timer = 0
      return function(callback, ms) {
        clearTimeout(timer)
        timer = setTimeout(callback, ms)
      }
    }, // 处理图片加载失败
    handlerImgError(e) {
      e.target.src = require('../../assets/img/errorImg.jpeg')
    },
    toRefresh() {
      this.fetchData(this.defaultPage, this.defaultLimit)
    },
    fetchData(page, limit) {
      this.listLoading = true
      var status = []
      var queryAll = ''
      var theme = ''
      if (this.status !== '-1') { status.push(this.statusMap[this.status - '1']); status = status.toString() }
      if (this.title !== '') { queryAll = this.title }
      if (this.category !== '') { theme = this.category[1] }
      getList({ page, limit, status, queryAll, theme }).then(response => {
        this.list = response.data.data.list
        this.list.map((item) => {
          item.title = this.brightKeyword(item.title)
        })
        this.pageInfo = response.data.data
        this.listLoading = false
      })
    },
    handleCurrentChange(page) {
      this.fetchData(page, this.defaultLimit)
    },
    // 文章的操作
    deleteArticle(id, title) {
      this.$confirm('确定要删除文章《' + title.replaceAll('<*>', '') + '》吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArticle(id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.toRefresh()
        })
      })
    },
    brightKeyword(val) {
      const keyword = this.title // 获取输入框输入的内容
      if (keyword === '') { return val }
      // 匹配关键字正则
      const replaceReg = new RegExp(keyword, 'gi')
      // 高亮替换v-html值
      const replaceString = '<span class="search-text">' + this.title + '</span>'
      // 开始替换
      val = val.replace(replaceReg, replaceString)
      console.log(val)
      return val
    }
  }
}
</script>
<style scoped>
.app-container-table{
  margin-left: 20px;
}
* {
  font-size: medium;
}
.el-tag {
  margin: 0 5px;
}
 .el-pagination {
  margin-top: 10px;
}
 .header{
   margin-top: 60px;
  margin-bottom: 30px;
  margin-right: 10px;
}
 .header div{
  display: inline-block;
  margin-right: 20px;
}
.header .select-title {
  font-size: 16px;
  font-weight: bold;
  padding-right: 30px;
}
 .select-scan  {
  display: flex;
   width: 400px;
}
.select-scan input{
  width: 500px;
}

</style>
